<?php


namespace app\admin\business;

use app\common\model\mysql\AdminUser as AdminUserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class AdminUser
{
    public static function login($data){
        try {
            $adminUserObj = new AdminUserModel();
            $adminUser = self::getAdminUserByUsername($data['username']);
            if (empty($adminUser)){
                throw new Exception('不存在该用户');
            }
            // 判断密码是否正确
            if ($adminUser['password'] != md5($data['password'])) {
                throw new Exception('密码不正确');
//                return show(config('status.error'), '密码不正确');
            }

            $updateData = [
                'last_login_time' => time(),
                'last_login_ip' => request()->ip(),
                'update_time' =>time()
            ];
            // 需要记录信息到MySQL表中
            $res = $adminUserObj->updateByID($adminUser['id'], $updateData);
            if (empty($res)) {
                return show(config('status.error'), '登录失败');
            }
        }catch (\Exception $e){
            // todo 记录日志 $e->getMessage()
            throw new Exception($e->getMessage());
//            return show(config('status.error'), '内部异常，登录失败');
        }
        // 记录session
        session(config('admin.session_admin'),$adminUser);

        return true;
    }

    /**
     * 通过用户名获取数据
     * @param $username
     * @return array|false
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAdminUserByUsername($username){

        $adminUserObj = new AdminUserModel();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);

        if (empty($adminUser) || $adminUser->status != config('status.mysql.table_normal')) {
            return false;
        }

        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}